home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / unittest.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  35KB  |  981 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. Python unit testing framework, based on Erich Gamma\'s JUnit and Kent Beck\'s
  6. Smalltalk testing framework.
  7.  
  8. This module contains the core framework classes that form the basis of
  9. specific test cases and suites (TestCase, TestSuite etc.), and also a
  10. text-based utility class for running the tests and reporting the results
  11.  (TextTestRunner).
  12.  
  13. Simple usage:
  14.  
  15.     import unittest
  16.  
  17.     class IntegerArithmenticTestCase(unittest.TestCase):
  18.         def testAdd(self):  ## test method names begin \'test*\'
  19.             self.assertEquals((1 + 2), 3)
  20.             self.assertEquals(0 + 1, 1)
  21.         def testMultiply(self):
  22.             self.assertEquals((0 * 10), 0)
  23.             self.assertEquals((5 * 8), 40)
  24.  
  25.     if __name__ == \'__main__\':
  26.         unittest.main()
  27.  
  28. Further information is available in the bundled documentation, and from
  29.  
  30.   http://docs.python.org/lib/module-unittest.html
  31.  
  32. Copyright (c) 1999-2003 Steve Purcell
  33. This module is free software, and you may redistribute it and/or modify
  34. it under the same terms as Python itself, so long as this copyright message
  35. and disclaimer are retained in their original form.
  36.  
  37. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  38. SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  39. THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  40. DAMAGE.
  41.  
  42. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  43. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  44. PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  45. AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  46. SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  47. '''
  48. __author__ = 'Steve Purcell'
  49. __email__ = 'stephen_purcell at yahoo dot com'
  50. __version__ = '#Revision: 1.63 $'[11:-2]
  51. import time
  52. import sys
  53. import traceback
  54. import os
  55. import types
  56. __all__ = [
  57.     'TestResult',
  58.     'TestCase',
  59.     'TestSuite',
  60.     'TextTestRunner',
  61.     'TestLoader',
  62.     'FunctionTestCase',
  63.     'main',
  64.     'defaultTestLoader']
  65. __all__.extend([
  66.     'getTestCaseNames',
  67.     'makeSuite',
  68.     'findTestCases'])
  69. if sys.version_info[:2] < (2, 2):
  70.     
  71.     def isinstance(obj, clsinfo):
  72.         import __builtin__ as __builtin__
  73.         if type(clsinfo) in (tuple, list):
  74.             for cls in clsinfo:
  75.                 if cls is type:
  76.                     cls = types.ClassType
  77.                 
  78.                 if __builtin__.isinstance(obj, cls):
  79.                     return 1
  80.             
  81.             return 0
  82.         return __builtin__.isinstance(obj, clsinfo)
  83.  
  84.  
  85.  
  86. def _CmpToKey(mycmp):
  87.     '''Convert a cmp= function into a key= function'''
  88.     
  89.     class K((object,)):
  90.         
  91.         def __init__(self, obj):
  92.             self.obj = obj
  93.  
  94.         
  95.         def __lt__(self, other):
  96.             return mycmp(self.obj, other.obj) == -1
  97.  
  98.  
  99.     return K
  100.  
  101. __metaclass__ = type
  102.  
  103. def _strclass(cls):
  104.     return '%s.%s' % (cls.__module__, cls.__name__)
  105.  
  106. __unittest = 1
  107.  
  108. class TestResult:
  109.     '''Holder for test result information.
  110.  
  111.     Test results are automatically managed by the TestCase and TestSuite
  112.     classes, and do not need to be explicitly manipulated by writers of tests.
  113.  
  114.     Each instance holds the total number of tests run, and collections of
  115.     failures and errors that occurred among those test runs. The collections
  116.     contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
  117.     formatted traceback of the error that occurred.
  118.     '''
  119.     
  120.     def __init__(self):
  121.         self.failures = []
  122.         self.errors = []
  123.         self.testsRun = 0
  124.         self.shouldStop = False
  125.  
  126.     
  127.     def startTest(self, test):
  128.         '''Called when the given test is about to be run'''
  129.         self.testsRun = self.testsRun + 1
  130.  
  131.     
  132.     def stopTest(self, test):
  133.         '''Called when the given test has been run'''
  134.         pass
  135.  
  136.     
  137.     def addError(self, test, err):
  138.         """Called when an error has occurred. 'err' is a tuple of values as
  139.         returned by sys.exc_info().
  140.         """
  141.         self.errors.append((test, self._exc_info_to_string(err, test)))
  142.  
  143.     
  144.     def addFailure(self, test, err):
  145.         """Called when an error has occurred. 'err' is a tuple of values as
  146.         returned by sys.exc_info()."""
  147.         self.failures.append((test, self._exc_info_to_string(err, test)))
  148.  
  149.     
  150.     def addSuccess(self, test):
  151.         '''Called when a test has completed successfully'''
  152.         pass
  153.  
  154.     
  155.     def wasSuccessful(self):
  156.         '''Tells whether or not this result was a success'''
  157.         if len(self.errors) == len(self.errors):
  158.             return len(self.errors) == 0
  159.         len(self.errors) == len(self.errors)
  160.         return len(self.errors)
  161.  
  162.     
  163.     def stop(self):
  164.         '''Indicates that the tests should be aborted'''
  165.         self.shouldStop = True
  166.  
  167.     
  168.     def _exc_info_to_string(self, err, test):
  169.         '''Converts a sys.exc_info()-style tuple of values into a string.'''
  170.         (exctype, value, tb) = err
  171.         while tb and self._is_relevant_tb_level(tb):
  172.             tb = tb.tb_next
  173.         if exctype is test.failureException:
  174.             length = self._count_relevant_tb_levels(tb)
  175.             return ''.join(traceback.format_exception(exctype, value, tb, length))
  176.         return ''.join(traceback.format_exception(exctype, value, tb))
  177.  
  178.     
  179.     def _is_relevant_tb_level(self, tb):
  180.         return '__unittest' in tb.tb_frame.f_globals
  181.  
  182.     
  183.     def _count_relevant_tb_levels(self, tb):
  184.         length = 0
  185.         while tb and not self._is_relevant_tb_level(tb):
  186.             length += 1
  187.             tb = tb.tb_next
  188.         return length
  189.  
  190.     
  191.     def __repr__(self):
  192.         return '<%s run=%i errors=%i failures=%i>' % (_strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures))
  193.  
  194.  
  195.  
  196. class TestCase:
  197.     """A class whose instances are single test cases.
  198.  
  199.     By default, the test code itself should be placed in a method named
  200.     'runTest'.
  201.  
  202.     If the fixture may be used for many test cases, create as
  203.     many test methods as are needed. When instantiating such a TestCase
  204.     subclass, specify in the constructor arguments the name of the test method
  205.     that the instance is to execute.
  206.  
  207.     Test authors should subclass TestCase for their own tests. Construction
  208.     and deconstruction of the test's environment ('fixture') can be
  209.     implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  210.  
  211.     If it is necessary to override the __init__ method, the base class
  212.     __init__ method must always be called. It is important that subclasses
  213.     should not change the signature of their __init__ method, since instances
  214.     of the classes are instantiated automatically by parts of the framework
  215.     in order to be run.
  216.     """
  217.     failureException = AssertionError
  218.     
  219.     def __init__(self, methodName = 'runTest'):
  220.         '''Create an instance of the class that will use the named test
  221.            method when executed. Raises a ValueError if the instance does
  222.            not have a method with the specified name.
  223.         '''
  224.         
  225.         try:
  226.             self._testMethodName = methodName
  227.             testMethod = getattr(self, methodName)
  228.             self._testMethodDoc = testMethod.__doc__
  229.         except AttributeError:
  230.             raise ValueError, 'no such test method in %s: %s' % (self.__class__, methodName)
  231.  
  232.  
  233.     
  234.     def setUp(self):
  235.         '''Hook method for setting up the test fixture before exercising it.'''
  236.         pass
  237.  
  238.     
  239.     def tearDown(self):
  240.         '''Hook method for deconstructing the test fixture after testing it.'''
  241.         pass
  242.  
  243.     
  244.     def countTestCases(self):
  245.         return 1
  246.  
  247.     
  248.     def defaultTestResult(self):
  249.         return TestResult()
  250.  
  251.     
  252.     def shortDescription(self):
  253.         """Returns a one-line description of the test, or None if no
  254.         description has been provided.
  255.  
  256.         The default implementation of this method returns the first line of
  257.         the specified test method's docstring.
  258.         """
  259.         doc = self._testMethodDoc
  260.         if not doc or doc.split('\n')[0].strip():
  261.             pass
  262.  
  263.     
  264.     def id(self):
  265.         return '%s.%s' % (_strclass(self.__class__), self._testMethodName)
  266.  
  267.     
  268.     def __eq__(self, other):
  269.         if type(self) is not type(other):
  270.             return False
  271.         return self._testMethodName == other._testMethodName
  272.  
  273.     
  274.     def __ne__(self, other):
  275.         return not (self == other)
  276.  
  277.     
  278.     def __hash__(self):
  279.         return hash((type(self), self._testMethodName))
  280.  
  281.     
  282.     def __str__(self):
  283.         return '%s (%s)' % (self._testMethodName, _strclass(self.__class__))
  284.  
  285.     
  286.     def __repr__(self):
  287.         return '<%s testMethod=%s>' % (_strclass(self.__class__), self._testMethodName)
  288.  
  289.     
  290.     def run(self, result = None):
  291.         if result is None:
  292.             result = self.defaultTestResult()
  293.         
  294.         result.startTest(self)
  295.         testMethod = getattr(self, self._testMethodName)
  296.         
  297.         try:
  298.             self.setUp()
  299.         except KeyboardInterrupt:
  300.             raise 
  301.         except:
  302.             result.addError(self, self._exc_info())
  303.             return None
  304.         
  305.  
  306.         ok = False
  307.         
  308.         try:
  309.             testMethod()
  310.             ok = True
  311.         except self.failureException:
  312.             result.addFailure(self, self._exc_info())
  313.         except KeyboardInterrupt:
  314.             raise 
  315.         except:
  316.             result.addError(self, self._exc_info())
  317.  
  318.         
  319.         try:
  320.             self.tearDown()
  321.         except KeyboardInterrupt:
  322.             raise 
  323.         except:
  324.             result.addError(self, self._exc_info())
  325.             ok = False
  326.  
  327.         if ok:
  328.             result.addSuccess(self)
  329.         result.stopTest(self)
  330.  
  331.     
  332.     def __call__(self, *args, **kwds):
  333.         return self.run(*args, **kwds)
  334.  
  335.     
  336.     def debug(self):
  337.         '''Run the test without collecting errors in a TestResult'''
  338.         self.setUp()
  339.         getattr(self, self._testMethodName)()
  340.         self.tearDown()
  341.  
  342.     
  343.     def _exc_info(self):
  344.         '''Return a version of sys.exc_info() with the traceback frame
  345.            minimised; usually the top level of the traceback frame is not
  346.            needed.
  347.         '''
  348.         return sys.exc_info()
  349.  
  350.     
  351.     def fail(self, msg = None):
  352.         '''Fail immediately, with the given message.'''
  353.         raise self.failureException, msg
  354.  
  355.     
  356.     def failIf(self, expr, msg = None):
  357.         '''Fail the test if the expression is true.'''
  358.         if expr:
  359.             raise self.failureException, msg
  360.         expr
  361.  
  362.     
  363.     def failUnless(self, expr, msg = None):
  364.         '''Fail the test unless the expression is true.'''
  365.         if not expr:
  366.             raise self.failureException, msg
  367.         expr
  368.  
  369.     
  370.     def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
  371.         '''Fail unless an exception of class excClass is thrown
  372.            by callableObj when invoked with arguments args and keyword
  373.            arguments kwargs. If a different type of exception is
  374.            thrown, it will not be caught, and the test case will be
  375.            deemed to have suffered an error, exactly as for an
  376.            unexpected exception.
  377.         '''
  378.         
  379.         try:
  380.             callableObj(*args, **kwargs)
  381.         except excClass:
  382.             return None
  383.  
  384.         if hasattr(excClass, '__name__'):
  385.             excName = excClass.__name__
  386.         else:
  387.             excName = str(excClass)
  388.         raise self.failureException, '%s not raised' % excName
  389.  
  390.     
  391.     def failUnlessEqual(self, first, second, msg = None):
  392.         """Fail if the two objects are unequal as determined by the '=='
  393.            operator.
  394.         """
  395.         if not first == second:
  396.             if not msg:
  397.                 pass
  398.             raise self.failureException, '%r != %r' % (first, second)
  399.         first == second
  400.  
  401.     
  402.     def failIfEqual(self, first, second, msg = None):
  403.         """Fail if the two objects are equal as determined by the '=='
  404.            operator.
  405.         """
  406.         if first == second:
  407.             if not msg:
  408.                 pass
  409.             raise self.failureException, '%r == %r' % (first, second)
  410.         first == second
  411.  
  412.     
  413.     def failUnlessAlmostEqual(self, first, second, places = 7, msg = None):
  414.         '''Fail if the two objects are unequal as determined by their
  415.            difference rounded to the given number of decimal places
  416.            (default 7) and comparing to zero.
  417.  
  418.            Note that decimal places (from zero) are usually not the same
  419.            as significant digits (measured from the most signficant digit).
  420.         '''
  421.         if round(abs(second - first), places) != 0:
  422.             if not msg:
  423.                 pass
  424.             raise self.failureException, '%r != %r within %r places' % (first, second, places)
  425.         round(abs(second - first), places) != 0
  426.  
  427.     
  428.     def failIfAlmostEqual(self, first, second, places = 7, msg = None):
  429.         '''Fail if the two objects are equal as determined by their
  430.            difference rounded to the given number of decimal places
  431.            (default 7) and comparing to zero.
  432.  
  433.            Note that decimal places (from zero) are usually not the same
  434.            as significant digits (measured from the most signficant digit).
  435.         '''
  436.         if round(abs(second - first), places) == 0:
  437.             if not msg:
  438.                 pass
  439.             raise self.failureException, '%r == %r within %r places' % (first, second, places)
  440.         round(abs(second - first), places) == 0
  441.  
  442.     assertEqual = assertEquals = failUnlessEqual
  443.     assertNotEqual = assertNotEquals = failIfEqual
  444.     assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
  445.     assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
  446.     assertRaises = failUnlessRaises
  447.     assert_ = assertTrue = failUnless
  448.     assertFalse = failIf
  449.  
  450.  
  451. class TestSuite:
  452.     '''A test suite is a composite test consisting of a number of TestCases.
  453.  
  454.     For use, create an instance of TestSuite, then add test case instances.
  455.     When all tests have been added, the suite can be passed to a test
  456.     runner, such as TextTestRunner. It will run the individual test cases
  457.     in the order in which they were added, aggregating the results. When
  458.     subclassing, do not forget to call the base class constructor.
  459.     '''
  460.     
  461.     def __init__(self, tests = ()):
  462.         self._tests = []
  463.         self.addTests(tests)
  464.  
  465.     
  466.     def __repr__(self):
  467.         return '<%s tests=%s>' % (_strclass(self.__class__), self._tests)
  468.  
  469.     __str__ = __repr__
  470.     
  471.     def __eq__(self, other):
  472.         if type(self) is not type(other):
  473.             return False
  474.         return self._tests == other._tests
  475.  
  476.     
  477.     def __ne__(self, other):
  478.         return not (self == other)
  479.  
  480.     __hash__ = None
  481.     
  482.     def __iter__(self):
  483.         return iter(self._tests)
  484.  
  485.     
  486.     def countTestCases(self):
  487.         cases = 0
  488.         for test in self._tests:
  489.             cases += test.countTestCases()
  490.         
  491.         return cases
  492.  
  493.     
  494.     def addTest(self, test):
  495.         if not hasattr(test, '__call__'):
  496.             raise TypeError('the test to add must be callable')
  497.         hasattr(test, '__call__')
  498.         if isinstance(test, (type, types.ClassType)) and issubclass(test, (TestCase, TestSuite)):
  499.             raise TypeError('TestCases and TestSuites must be instantiated before passing them to addTest()')
  500.         issubclass(test, (TestCase, TestSuite))
  501.         self._tests.append(test)
  502.  
  503.     
  504.     def addTests(self, tests):
  505.         if isinstance(tests, basestring):
  506.             raise TypeError('tests must be an iterable of tests, not a string')
  507.         isinstance(tests, basestring)
  508.         for test in tests:
  509.             self.addTest(test)
  510.         
  511.  
  512.     
  513.     def run(self, result):
  514.         for test in self._tests:
  515.             if result.shouldStop:
  516.                 break
  517.             
  518.             test(result)
  519.         
  520.         return result
  521.  
  522.     
  523.     def __call__(self, *args, **kwds):
  524.         return self.run(*args, **kwds)
  525.  
  526.     
  527.     def debug(self):
  528.         '''Run the tests without collecting errors in a TestResult'''
  529.         for test in self._tests:
  530.             test.debug()
  531.         
  532.  
  533.  
  534.  
  535. class FunctionTestCase(TestCase):
  536.     """A test case that wraps a test function.
  537.  
  538.     This is useful for slipping pre-existing test functions into the
  539.     unittest framework. Optionally, set-up and tidy-up functions can be
  540.     supplied. As with TestCase, the tidy-up ('tearDown') function will
  541.     always be called if the set-up ('setUp') function ran successfully.
  542.     """
  543.     
  544.     def __init__(self, testFunc, setUp = None, tearDown = None, description = None):
  545.         TestCase.__init__(self)
  546.         self._FunctionTestCase__setUpFunc = setUp
  547.         self._FunctionTestCase__tearDownFunc = tearDown
  548.         self._FunctionTestCase__testFunc = testFunc
  549.         self._FunctionTestCase__description = description
  550.  
  551.     
  552.     def setUp(self):
  553.         if self._FunctionTestCase__setUpFunc is not None:
  554.             self._FunctionTestCase__setUpFunc()
  555.         
  556.  
  557.     
  558.     def tearDown(self):
  559.         if self._FunctionTestCase__tearDownFunc is not None:
  560.             self._FunctionTestCase__tearDownFunc()
  561.         
  562.  
  563.     
  564.     def runTest(self):
  565.         self._FunctionTestCase__testFunc()
  566.  
  567.     
  568.     def id(self):
  569.         return self._FunctionTestCase__testFunc.__name__
  570.  
  571.     
  572.     def __eq__(self, other):
  573.         return type(self) is not type(other) if type(self) is not type(other) else self._FunctionTestCase__description == other._FunctionTestCase__description
  574.  
  575.     
  576.     def __ne__(self, other):
  577.         return not (self == other)
  578.  
  579.     
  580.     def __hash__(self):
  581.         return hash((type(self), self._FunctionTestCase__setUpFunc, self._FunctionTestCase__tearDownFunc, self._FunctionTestCase__testFunc, self._FunctionTestCase__description))
  582.  
  583.     
  584.     def __str__(self):
  585.         return '%s (%s)' % (_strclass(self.__class__), self._FunctionTestCase__testFunc.__name__)
  586.  
  587.     
  588.     def __repr__(self):
  589.         return '<%s testFunc=%s>' % (_strclass(self.__class__), self._FunctionTestCase__testFunc)
  590.  
  591.     
  592.     def shortDescription(self):
  593.         if self._FunctionTestCase__description is not None:
  594.             return self._FunctionTestCase__description
  595.         doc = self._FunctionTestCase__testFunc.__doc__
  596.         if not doc or doc.split('\n')[0].strip():
  597.             pass
  598.  
  599.  
  600.  
  601. class TestLoader:
  602.     '''This class is responsible for loading tests according to various
  603.     criteria and returning them wrapped in a TestSuite
  604.     '''
  605.     testMethodPrefix = 'test'
  606.     sortTestMethodsUsing = cmp
  607.     suiteClass = TestSuite
  608.     
  609.     def loadTestsFromTestCase(self, testCaseClass):
  610.         '''Return a suite of all tests cases contained in testCaseClass'''
  611.         if issubclass(testCaseClass, TestSuite):
  612.             raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
  613.         issubclass(testCaseClass, TestSuite)
  614.         testCaseNames = self.getTestCaseNames(testCaseClass)
  615.         if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  616.             testCaseNames = [
  617.                 'runTest']
  618.         
  619.         return self.suiteClass(map(testCaseClass, testCaseNames))
  620.  
  621.     
  622.     def loadTestsFromModule(self, module):
  623.         '''Return a suite of all tests cases contained in the given module'''
  624.         tests = []
  625.         for name in dir(module):
  626.             obj = getattr(module, name)
  627.             if isinstance(obj, (type, types.ClassType)) and issubclass(obj, TestCase):
  628.                 tests.append(self.loadTestsFromTestCase(obj))
  629.                 continue
  630.         
  631.         return self.suiteClass(tests)
  632.  
  633.     
  634.     def loadTestsFromName(self, name, module = None):
  635.         '''Return a suite of all tests cases given a string specifier.
  636.  
  637.         The name may resolve either to a module, a test case class, a
  638.         test method within a test case class, or a callable object which
  639.         returns a TestCase or TestSuite instance.
  640.  
  641.         The method optionally resolves the names relative to a given module.
  642.         '''
  643.         parts = name.split('.')
  644.         if module is None:
  645.             parts_copy = parts[:]
  646.             while parts_copy:
  647.                 
  648.                 try:
  649.                     module = __import__('.'.join(parts_copy))
  650.                 continue
  651.                 except ImportError:
  652.                     del parts_copy[-1]
  653.                     if not parts_copy:
  654.                         raise 
  655.                     parts_copy
  656.                     continue
  657.                 
  658.  
  659.                 None<EXCEPTION MATCH>ImportError
  660.             parts = parts[1:]
  661.         
  662.         obj = module
  663.         for part in parts:
  664.             parent = obj
  665.             obj = getattr(obj, part)
  666.         
  667.         if type(obj) == types.ModuleType:
  668.             return self.loadTestsFromModule(obj)
  669.         if isinstance(obj, (type, types.ClassType)) and issubclass(obj, TestCase):
  670.             return self.loadTestsFromTestCase(obj)
  671.         if type(obj) == types.UnboundMethodType and isinstance(parent, (type, types.ClassType)) and issubclass(parent, TestCase):
  672.             return TestSuite([
  673.                 parent(obj.__name__)])
  674.         if isinstance(obj, TestSuite):
  675.             return obj
  676.         if hasattr(obj, '__call__'):
  677.             test = obj()
  678.             if isinstance(test, TestSuite):
  679.                 return test
  680.             if isinstance(test, TestCase):
  681.                 return TestSuite([
  682.                     test])
  683.             raise TypeError('calling %s returned %s, not a test' % (obj, test))
  684.         hasattr(obj, '__call__')
  685.         raise TypeError("don't know how to make test from: %s" % obj)
  686.  
  687.     
  688.     def loadTestsFromNames(self, names, module = None):
  689.         """Return a suite of all tests cases found using the given sequence
  690.         of string specifiers. See 'loadTestsFromName()'.
  691.         """
  692.         suites = [ self.loadTestsFromName(name, module) for name in names ]
  693.         return self.suiteClass(suites)
  694.  
  695.     
  696.     def getTestCaseNames(self, testCaseClass):
  697.         '''Return a sorted sequence of method names found within testCaseClass
  698.         '''
  699.         
  700.         def isTestMethod(attrname, testCaseClass = testCaseClass, prefix = self.testMethodPrefix):
  701.             if attrname.startswith(prefix):
  702.                 pass
  703.             return hasattr(getattr(testCaseClass, attrname), '__call__')
  704.  
  705.         testFnNames = filter(isTestMethod, dir(testCaseClass))
  706.         if self.sortTestMethodsUsing:
  707.             testFnNames.sort(key = _CmpToKey(self.sortTestMethodsUsing))
  708.         
  709.         return testFnNames
  710.  
  711.  
  712. defaultTestLoader = TestLoader()
  713.  
  714. def _makeLoader(prefix, sortUsing, suiteClass = None):
  715.     loader = TestLoader()
  716.     loader.sortTestMethodsUsing = sortUsing
  717.     loader.testMethodPrefix = prefix
  718.     if suiteClass:
  719.         loader.suiteClass = suiteClass
  720.     
  721.     return loader
  722.  
  723.  
  724. def getTestCaseNames(testCaseClass, prefix, sortUsing = cmp):
  725.     return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  726.  
  727.  
  728. def makeSuite(testCaseClass, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  729.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  730.  
  731.  
  732. def findTestCases(module, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  733.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  734.  
  735.  
  736. class _WritelnDecorator:
  737.     """Used to decorate file-like objects with a handy 'writeln' method"""
  738.     
  739.     def __init__(self, stream):
  740.         self.stream = stream
  741.  
  742.     
  743.     def __getattr__(self, attr):
  744.         return getattr(self.stream, attr)
  745.  
  746.     
  747.     def writeln(self, arg = None):
  748.         if arg:
  749.             self.write(arg)
  750.         
  751.         self.write('\n')
  752.  
  753.  
  754.  
  755. class _TextTestResult(TestResult):
  756.     '''A test result class that can print formatted text results to a stream.
  757.  
  758.     Used by TextTestRunner.
  759.     '''
  760.     separator1 = '=' * 70
  761.     separator2 = '-' * 70
  762.     
  763.     def __init__(self, stream, descriptions, verbosity):
  764.         TestResult.__init__(self)
  765.         self.stream = stream
  766.         self.showAll = verbosity > 1
  767.         self.dots = verbosity == 1
  768.         self.descriptions = descriptions
  769.  
  770.     
  771.     def getDescription(self, test):
  772.         if self.descriptions:
  773.             if not test.shortDescription():
  774.                 pass
  775.             return str(test)
  776.         return str(test)
  777.  
  778.     
  779.     def startTest(self, test):
  780.         TestResult.startTest(self, test)
  781.         if self.showAll:
  782.             self.stream.write(self.getDescription(test))
  783.             self.stream.write(' ... ')
  784.             self.stream.flush()
  785.         
  786.  
  787.     
  788.     def addSuccess(self, test):
  789.         TestResult.addSuccess(self, test)
  790.         if self.showAll:
  791.             self.stream.writeln('ok')
  792.         elif self.dots:
  793.             self.stream.write('.')
  794.             self.stream.flush()
  795.         
  796.  
  797.     
  798.     def addError(self, test, err):
  799.         TestResult.addError(self, test, err)
  800.         if self.showAll:
  801.             self.stream.writeln('ERROR')
  802.         elif self.dots:
  803.             self.stream.write('E')
  804.             self.stream.flush()
  805.         
  806.  
  807.     
  808.     def addFailure(self, test, err):
  809.         TestResult.addFailure(self, test, err)
  810.         if self.showAll:
  811.             self.stream.writeln('FAIL')
  812.         elif self.dots:
  813.             self.stream.write('F')
  814.             self.stream.flush()
  815.         
  816.  
  817.     
  818.     def printErrors(self):
  819.         if self.dots or self.showAll:
  820.             self.stream.writeln()
  821.         
  822.         self.printErrorList('ERROR', self.errors)
  823.         self.printErrorList('FAIL', self.failures)
  824.  
  825.     
  826.     def printErrorList(self, flavour, errors):
  827.         for test, err in errors:
  828.             self.stream.writeln(self.separator1)
  829.             self.stream.writeln('%s: %s' % (flavour, self.getDescription(test)))
  830.             self.stream.writeln(self.separator2)
  831.             self.stream.writeln('%s' % err)
  832.         
  833.  
  834.  
  835.  
  836. class TextTestRunner:
  837.     '''A test runner class that displays results in textual form.
  838.  
  839.     It prints out the names of tests as they are run, errors as they
  840.     occur, and a summary of the results at the end of the test run.
  841.     '''
  842.     
  843.     def __init__(self, stream = sys.stderr, descriptions = 1, verbosity = 1):
  844.         self.stream = _WritelnDecorator(stream)
  845.         self.descriptions = descriptions
  846.         self.verbosity = verbosity
  847.  
  848.     
  849.     def _makeResult(self):
  850.         return _TextTestResult(self.stream, self.descriptions, self.verbosity)
  851.  
  852.     
  853.     def run(self, test):
  854.         '''Run the given test case or test suite.'''
  855.         result = self._makeResult()
  856.         startTime = time.time()
  857.         test(result)
  858.         stopTime = time.time()
  859.         timeTaken = stopTime - startTime
  860.         result.printErrors()
  861.         self.stream.writeln(result.separator2)
  862.         run = result.testsRun
  863.         if not run != 1 or 's':
  864.             pass
  865.         self.stream.writeln('Ran %d test%s in %.3fs' % (run, '', timeTaken))
  866.         self.stream.writeln()
  867.         if not result.wasSuccessful():
  868.             self.stream.write('FAILED (')
  869.             (failed, errored) = map(len, (result.failures, result.errors))
  870.             if failed:
  871.                 self.stream.write('failures=%d' % failed)
  872.             
  873.             if errored:
  874.                 if failed:
  875.                     self.stream.write(', ')
  876.                 
  877.                 self.stream.write('errors=%d' % errored)
  878.             
  879.             self.stream.writeln(')')
  880.         else:
  881.             self.stream.writeln('OK')
  882.         return result
  883.  
  884.  
  885.  
  886. class TestProgram:
  887.     '''A command-line program that runs a set of tests; this is primarily
  888.        for making test modules conveniently executable.
  889.     '''
  890.     USAGE = "Usage: %(progName)s [options] [test] [...]\n\nOptions:\n  -h, --help       Show this message\n  -v, --verbose    Verbose output\n  -q, --quiet      Minimal output\n\nExamples:\n  %(progName)s                               - run default set of tests\n  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'\n  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething\n  %(progName)s MyTestCase                    - run all 'test*' test methods\n                                               in MyTestCase\n"
  891.     
  892.     def __init__(self, module = '__main__', defaultTest = None, argv = None, testRunner = None, testLoader = defaultTestLoader):
  893.         if type(module) == type(''):
  894.             self.module = __import__(module)
  895.             for part in module.split('.')[1:]:
  896.                 self.module = getattr(self.module, part)
  897.             
  898.         else:
  899.             self.module = module
  900.         if argv is None:
  901.             argv = sys.argv
  902.         
  903.         self.verbosity = 1
  904.         self.defaultTest = defaultTest
  905.         self.testRunner = testRunner
  906.         self.testLoader = testLoader
  907.         self.progName = os.path.basename(argv[0])
  908.         self.parseArgs(argv)
  909.         self.runTests()
  910.  
  911.     
  912.     def usageExit(self, msg = None):
  913.         if msg:
  914.             print msg
  915.         
  916.         print self.USAGE % self.__dict__
  917.         sys.exit(2)
  918.  
  919.     
  920.     def parseArgs(self, argv):
  921.         import getopt as getopt
  922.         
  923.         try:
  924.             (options, args) = getopt.getopt(argv[1:], 'hHvq', [
  925.                 'help',
  926.                 'verbose',
  927.                 'quiet'])
  928.             for opt, value in options:
  929.                 if opt in ('-h', '-H', '--help'):
  930.                     self.usageExit()
  931.                 
  932.                 if opt in ('-q', '--quiet'):
  933.                     self.verbosity = 0
  934.                 
  935.                 if opt in ('-v', '--verbose'):
  936.                     self.verbosity = 2
  937.                     continue
  938.             
  939.             if len(args) == 0 and self.defaultTest is None:
  940.                 self.test = self.testLoader.loadTestsFromModule(self.module)
  941.                 return None
  942.             if len(args) > 0:
  943.                 self.testNames = args
  944.             else:
  945.                 self.testNames = (self.defaultTest,)
  946.             self.createTests()
  947.         except getopt.error:
  948.             msg = None
  949.             self.usageExit(msg)
  950.  
  951.  
  952.     
  953.     def createTests(self):
  954.         self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module)
  955.  
  956.     
  957.     def runTests(self):
  958.         if self.testRunner is None:
  959.             self.testRunner = TextTestRunner
  960.         
  961.         if isinstance(self.testRunner, (type, types.ClassType)):
  962.             
  963.             try:
  964.                 testRunner = self.testRunner(verbosity = self.verbosity)
  965.             except TypeError:
  966.                 testRunner = self.testRunner()
  967.             except:
  968.                 None<EXCEPTION MATCH>TypeError
  969.             
  970.  
  971.         None<EXCEPTION MATCH>TypeError
  972.         testRunner = self.testRunner
  973.         result = testRunner.run(self.test)
  974.         sys.exit(not result.wasSuccessful())
  975.  
  976.  
  977. main = TestProgram
  978. if __name__ == '__main__':
  979.     main(module = None)
  980.  
  981.